<template>
  <view class="coupon-exchange-page">
    <!-- 导航栏 -->
    <NavBar title="优惠券兑换" />

    <!-- 兑换区域 -->
    <view class="exchange-card">
      <view class="card-title">优惠券兑换</view>
      <view class="exchange-form">
        <view class="input-group">
          <nut-input
            v-model="couponCode"
            placeholder="请输入优惠券兑换码"
            clearable
            maxlength="20"
            :border="false"
          >
            <template #left>
              <Shop size="16" />
            </template>
          </nut-input>
        </view>
        <nut-button type="primary" block @click="exchangeCoupon" :loading="exchanging">立即兑换</nut-button>
      </view>
      <view class="exchange-tips">
        <view class="tips-title">兑换说明：</view>
        <view class="tips-item">1. 请输入正确的优惠券兑换码</view>
        <view class="tips-item">2. 每个兑换码仅可兑换一次</view>
        <view class="tips-item">3. 兑换成功后可在"我的优惠券"中查看</view>
        <view class="tips-item">4. 如遇兑换问题，请联系客服</view>
      </view>
    </view>

    <!-- 最近兑换记录 -->
    <view class="exchange-history" v-if="exchangeHistory.length > 0">
      <view class="history-title">最近兑换记录</view>
      <view class="history-list">
        <view 
          v-for="(item, index) in exchangeHistory" 
          :key="index"
          class="history-item"
          @click="viewCouponDetail(item.couponId)"
        >
          <view class="history-info">
            <view class="coupon-name">{{ item.couponName }}</view>
            <view class="exchange-time">{{ item.exchangeTime }}</view>
          </view>
          <Right size="14" color="#999" />
        </view>
      </view>
    </view>

    <!-- 推荐优惠券 -->
    <view class="recommend-coupons">
      <view class="recommend-title">推荐优惠券</view>
      <view class="coupon-list">
        <view 
          v-for="(item, index) in recommendCoupons" 
          :key="index"
          class="coupon-item"
          @click="goCouponCenter"
        >
          <view class="coupon-left">
            <view class="coupon-amount">
              <text class="symbol">¥</text>
              <text class="value">{{ item.amount }}</text>
            </view>
            <view class="coupon-condition">满{{ item.minAmount }}元可用</view>
          </view>
          <view class="coupon-right">
            <view class="coupon-name">{{ item.name }}</view>
            <view class="coupon-scope">{{ item.scope }}</view>
            <view class="coupon-btn">
              <nut-button size="small" type="primary">去领取</nut-button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'
import { useLoading } from '@/hooks/useLoading'
import { Right } from '@nutui/icons-vue-taro'
import { Shop } from '@nutui/icons-vue-taro' // 使用Shop图标替代不存在的Coupon图标

// 优惠券码
const couponCode = ref('')

// 兑换状态
const exchanging = ref(false)

// 加载状态
const { loading, showLoading, hideLoading } = useLoading()

// 兑换记录
interface ExchangeRecord {
  couponId: string | number;
  couponName: string;
  exchangeTime: string;
}

const exchangeHistory = ref<ExchangeRecord[]>([])

// 推荐优惠券
const recommendCoupons = ref([
  {
    id: '101',
    name: '新人专享券',
    amount: '15',
    minAmount: '100',
    scope: '全场通用'
  },
  {
    id: '102',
    name: '满减优惠券',
    amount: '30',
    minAmount: '200',
    scope: '全场通用'
  }
])

// 兑换优惠券
const exchangeCoupon = async () => {
  if (!couponCode.value) {
    return Taro.showToast({
      title: '请输入优惠券码',
      icon: 'none'
    })
  }
  
  try {
    exchanging.value = true
    
    // 调用API兑换优惠券
    await userApi.exchangeCoupon(couponCode.value)
    
    Taro.showToast({
      title: '兑换成功',
      icon: 'success'
    })
    
    // 添加到兑换记录
    exchangeHistory.value.unshift({
      couponId: Date.now().toString(), // 模拟ID
      couponName: '新兑换的优惠券',
      exchangeTime: formatDate(new Date())
    })
    
    // 清空输入框
    couponCode.value = ''
    
  } catch (error) {
    console.error('兑换优惠券失败', error)
    Taro.showToast({
      title: '兑换失败，请检查优惠券码是否正确',
      icon: 'none'
    })
  } finally {
    exchanging.value = false
  }
}

// 获取兑换记录
const getExchangeHistory = async () => {
  try {
    showLoading('加载中...')
    
    // 这里应该调用获取兑换记录的API
    // 由于API中没有直接提供，使用模拟数据
    
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    exchangeHistory.value = [
      {
        couponId: '201',
        couponName: '满100减15优惠券',
        exchangeTime: '2023-06-10'
      },
      {
        couponId: '202',
        couponName: '满200减30优惠券',
        exchangeTime: '2023-06-05'
      },
      {
        couponId: '203',
        couponName: '满300减50优惠券',
        exchangeTime: '2023-05-28'
      }
    ]
    
  } catch (error) {
    console.error('获取兑换记录失败', error)
  } finally {
    hideLoading()
  }
}

// 查看优惠券详情
const viewCouponDetail = (couponId: string | number) => {
  Taro.navigateTo({
    url: `/pages/coupon/detail?id=${couponId}`
  })
}

// 去领券中心
const goCouponCenter = () => {
  Taro.navigateTo({
    url: '/pages/coupon/center'
  })
}

// 格式化日期
const formatDate = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 组件挂载时初始化
onMounted(() => {
  getExchangeHistory()
})
</script>

<style lang="scss" scoped>
.coupon-exchange-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 20px;
  
  .exchange-card {
    margin: 15px;
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .card-title {
      font-size: 18px;
      font-weight: 500;
      color: #333;
      margin-bottom: 20px;
      text-align: center;
    }
    
    .exchange-form {
      margin-bottom: 20px;
      
      .input-group {
        margin-bottom: 15px;
        background-color: #f8f8f8;
        border-radius: 8px;
        overflow: hidden;
        
        :deep(.nut-input) {
          --nut-input-border-bottom: none;
          padding: 12px 15px;
          
          .nut-icon {
            margin-right: 10px;
            color: #999;
          }
        }
      }
    }
    
    .exchange-tips {
      background-color: #f8f8f8;
      border-radius: 8px;
      padding: 15px;
      
      .tips-title {
        font-size: 14px;
        font-weight: 500;
        color: #666;
        margin-bottom: 8px;
      }
      
      .tips-item {
        font-size: 12px;
        color: #999;
        line-height: 1.6;
        margin-bottom: 5px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
  
  .exchange-history,
  .recommend-coupons {
    margin: 15px;
    background-color: #fff;
    border-radius: 12px;
    padding: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    .history-title,
    .recommend-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 15px;
      position: relative;
      padding-left: 10px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 3px;
        height: 16px;
        background-color: #fa2c19;
        border-radius: 3px;
      }
    }
    
    .history-list {
      .history-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .history-info {
          .coupon-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
          }
          
          .exchange-time {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
    
    .coupon-list {
      .coupon-item {
        position: relative;
        display: flex;
        margin-bottom: 15px;
        height: 80px;
        background: linear-gradient(to right, #fa2c19, #fa6419);
        border-radius: 8px;
        color: #fff;
        overflow: hidden;
        box-shadow: 0 2px 8px rgba(250, 44, 25, 0.2);
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .coupon-left {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 100px;
          border-right: 1px dashed rgba(255, 255, 255, 0.3);
          
          .coupon-amount {
            display: flex;
            align-items: baseline;
            
            .symbol {
              font-size: 14px;
              margin-right: 2px;
            }
            
            .value {
              font-size: 24px;
              font-weight: bold;
            }
          }
          
          .coupon-condition {
            font-size: 12px;
            margin-top: 5px;
          }
        }
        
        .coupon-right {
          flex: 1;
          padding: 12px;
          position: relative;
          
          .coupon-name {
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 150px;
          }
          
          .coupon-scope {
            font-size: 12px;
            opacity: 0.8;
            margin-bottom: 5px;
          }
          
          .coupon-btn {
            position: absolute;
            right: 12px;
            bottom: 12px;
          }
        }
      }
    }
  }
}
</style>